<template>
  <div class="common-app-box">
    <transition name="el-fade-in" mode="out-in">
      <template v-if="token">
        <el-menu
          :default-active="activeIndex"
          class="el-menu-demo"
          mode="horizontal"
          @select="handleSelect"
          background-color="#545c64"
          text-color="#fff"
          active-text-color="#ffd04b">
          <template v-for="menu in menuList">
            <el-menu-item v-if="!menu.children" :key="menu.path" :index="menu.path">{{ menu.name }}</el-menu-item>
            <el-submenu v-else :key="menu.path" :index="menu.path">
              <template slot="title">{{ menu.name }}</template>
              <!-- 二级目录 -->
              <template v-for="menu2 in menu.children">
                <el-menu-item v-if="!menu2.children" :key="menu2.path" :index="menu2.path">{{ menu2.name }}</el-menu-item>
                <el-submenu v-else :key="menu2.path" :index="menu2.path">
                  <template slot="title">{{ menu.name }}</template>
                  <!-- 三级目录 -->
                  <el-menu-item  v-for="menu3 in menu2.children" :key="menu3.path" :index="menu3.path">{{ menu3.name }}</el-menu-item>
                </el-submenu>
              </template>
            </el-submenu>
          </template>
        </el-menu>
      </template>
      <template v-else>
          <router-view />
      </template>
    </transition>
  </div>
</template>

<script>
import { mapGetters, mapMutations } from "vuex"
import { appMenus } from '../../../config/appServies'
import { getCookie } from '../../../utils/cookie'

// 不需要权限校验的白名单
const whiteList = ['/login']

export default {
  name: "vueApp",
  data() {
    return {
      menuList: [],
      activeIndex: ''
    };
  },
  computed: {
    ...mapGetters([
      'token'
    ])
  },
  watch: {
    // 通过监听切换监听token过期
    $route: {
      handler: function(val, oldVal){
        console.log('监听路由变化：', val.path)
        if (!whiteList.includes(val.path)) {
          this.init()
        }
      },
      immediate: true
    }
  },
  methods: {
    ...mapMutations([
      'setUserInfo'
    ]),
    init() {
      let token = window.ssaSdk.getToken()
      this.menuList = Object.entries(appMenus).map(arr => arr[1])
      console.log('菜单：', this.menuList)
      this.activeIndex = this.$route.path
      if (token) {
        this.setUserInfo({
          token,
          userName: decodeURIComponent(getCookie('userName')),
          userId: getCookie('userId')
        })
      }
    },
    handleSelect(key, keyPath) {
      this.activeIndex = key
      window.location.hash = `#${key}`
    }
  }
};
</script>

<style lang="less" scoped>
.common-app-box {
  .item {
    width: 120px;
    text-align: center;
    border-left: solid 1px #cccccc;
  }
}
</style>

